﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace 比大小
{
    public partial class Form1 : Form
    {
        private Thread th;
        //设置骰子的开始或停止的标识
        private bool flg = false;
        public Form1()
        {
            InitializeComponent();
        }

        private void btnBegin_Click(object sender, EventArgs e)
        {
            if(flg == false)
            {
                flg = true;
                btnBegin.Text = "停止";

                //线程调用PlayGanme
                th = new Thread(PlayGame);
                th.IsBackground = true;
                th.Name = "丢骰子";
                th.Start();
            }
            else
            {
                flg = false;
                btnBegin.Text = "开始";
            }

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //取消跨线程错误检测
            //默认跨线程操作危险，同样的一块内存区域，多个线程一起调用
            //例：同一个内存里的一个变量，这个线程说修改，那个线程说删除，发生冲突
            Control.CheckForIllegalCrossThreadCalls = false;
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            //当关闭窗体时，把后台线程也撒掉
            if (th != null)
            {
                th.Abort();
            }
        }

        private void PlayGame()
        {
            Random r = new Random();
            while (flg)
            {
                label1.Text = r.Next(1, 7).ToString();
                label2.Text = r.Next(1, 7).ToString();
                label3.Text = r.Next(1, 7).ToString();
            }
        }
    }
}
